# coding:utf-8
from django.shortcuts import render, redirect, HttpResponse
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from django.contrib import auth
from django.contrib.auth.models import Group,Permission
from django.contrib.auth.decorators import login_required
from .models import Users
from .forms import RegisterForm, CaptchaForm, ChangepasswordForm,ChangeimageForm
import hashlib

# Create your views here.
per_teacher_list =  ["add_students","change_students","delete_students","view_students",
                     "add_users","change_users","view_users"
                     ]
per_student_list = ["change_students","view_students",
                   "add_users","change_users","view_users"
                    ]
per_admin_list = ["add_users","change_users","delete_users","view_users",
                  "add_teachers","change_teachers","delete_teachers","view_teachers",
                  "add_students","change_students","delete_students","view_students"
                  ]
#密码加密
def hash_code(s, salt='student_system'):
    h = hashlib.sha256()
    s += salt
    h.update(s.encode())
    return h.hexdigest()

#创建用户组,并添加权限
def create_group():
    #组不存在则创建组
    if not (Group.objects.filter(name="teacher").exists()):
        group_teacher=Group.objects.create(name="teacher")
        #从auth_permission表中添加权限到auth_group_permission表中
        for p in per_teacher_list:
            permission = Permission.objects.get(codename=p)
            group_teacher.permissions.add(permission)
        group_teacher.save()

    if not (Group.objects.filter(name="student").exists()):
        group_student=Group.objects.create(name="student")
        for p in per_student_list:
            permission = Permission.objects.get(codename=p)
            group_student.permissions.add(permission)
        group_student.save()

    if not (Group.objects.filter(name="admin").exists()):
        group_admin = Group.objects.create(name="admin")
        for p in per_admin_list:
            permission = Permission.objects.get(codename=p)
            group_admin.permissions.add(permission)
        group_admin.save()

def index(request):
    create_group()
    #login_form = UserForm()
    #return render(request, 'login/login.html',{"login_form": login_form})
    captcha = CaptchaForm()
    return render(request, 'login/login.html', {"captcha_form": captcha})


# 登录视图
@csrf_exempt
def login(request):
    if request.method == "POST":
        captcha_form = CaptchaForm(request.POST)
        message = ""
        if captcha_form.is_valid():
            username = request.POST.get('userid')
            password = request.POST.get('userpwd')
            try:
                user = Users.objects.get(username=username)
                if user.password == hash_code(password):
                    auth.login(request,user) #进行登录操作，这样django才能记住当前的登录用户，以便接下来对该用户的登录状态和权限进行判断
                    request.session['is_login'] = True
                    request.session['user_id'] = user.id
                    request.session['user_name'] = user.username
                    request.session.set_expiry(0) #设置session的有效期为：退出浏览器就失效
                    user.set_visit_num()#更新访问量
                    return render(request, 'login/index.html')
                else:
                    message = "密码不正确"
            except Users.DoesNotExist:
                message = "用户不存在！"
        return render(request, 'login/login.html', {"message": message, "captcha_form": captcha_form})
    return redirect('/index/')


# 注册视图
def register(request):
    if request.method == "POST":
        register_form = RegisterForm(request.POST)
        message = "请检查填写的内容！"
        if register_form.is_valid():  # 获取数据
            username = register_form.cleaned_data['username']
            password1 = register_form.cleaned_data['password1']
            password2 = register_form.cleaned_data['password2']
            email = register_form.cleaned_data['email']
            sex = register_form.cleaned_data['sex']
            utype = register_form.cleaned_data['usertype']
            if password1 != password2:  # 判断两次密码是否相同
                message = "两次输入的密码不同！"
            else:
                same_name_user = Users.objects.filter(username=username)
                if same_name_user:  # 用户名唯一
                    message = '用户已经存在，请重新选择用户名！'
                    return render(request, 'login/register.html', {"message": message, "register_form": register_form})
                same_email_user = Users.objects.filter(email=email)
                if same_email_user:  # 邮箱地址唯一
                    message = '该邮箱地址已被注册，请使用别的邮箱！'
                    return render(request, 'login/register.html', {"message": message, "register_form": register_form})
                # 当一切都OK的情况下，创建新用户
                new_user = Users.objects.create()
                new_user.username = username
                new_user.password = hash_code(password1)
                new_user.email = email
                new_user.sex = sex
                new_user.usertype = utype
                if utype =='1':
                    group_teacher=Group.objects.filter(name="teacher").first()
                    group_teacher.user_set.add(new_user)
                if utype =='2':
                    group_student=Group.objects.filter(name="student").first()
                    group_student.user_set.add(new_user)
                if utype =='3':
                    group_admin=Group.objects.filter(name="admin").first()
                    group_admin.user_set.add(new_user)
                new_user.save()
                return redirect('/index/')  # 自动跳转到登录页面
        return render(request, 'login/register.html', {"message": message, "register_form": register_form})
    register_form = RegisterForm()
    return render(request, 'login/register.html', {"register_form": register_form})


# 注销视图
def logout(request):
    if not request.session.get('is_login', None):
        # 如果本来就未登录，也就没有注销一说
        return redirect("/index/")
    auth.logout(request)
    request.session.flush()
    return redirect('/index/')
# 或者使用下面的方法
    # del request.session['is_login']
    # del request.session['user_id']
    # del request.session['user_name']

@login_required(login_url='/loginurl/')
def changepassword(request):
    if request.method =="POST":
        changepassword_form = ChangepasswordForm(request.POST)
        message = ""
        if changepassword_form.is_valid():
            password = changepassword_form.cleaned_data['password']
            password1 = changepassword_form.cleaned_data['password1']
            password2 =changepassword_form.cleaned_data['password2']
            if password1 != password2:  # 判断两次密码是否相同
                message = "两次输入的密码不同！"
            else:
                user = Users.objects.filter(username= request.session['user_name'])
                if hash_code(password) != user.first().password:
                     message = "原密码错误！"
                else:
                    user.update(password=hash_code(password1))
                    return redirect('/index/')  # 自动跳转到登录页面
        return render(request,'login/changepassword.html',{"message":message, "changepassword_form":changepassword_form})
    changepassword_form = ChangepasswordForm()
    return render(request,'login/changepassword.html',{"changepassword_form":changepassword_form})

@login_required(login_url='/loginurl/')
def changeimage(request):
    if request.method == "POST":
        changeimage_form = ChangeimageForm(request.POST,request.FILES)
        if changeimage_form.is_valid():
            image = changeimage_form.cleaned_data['image']
            user = request.user
            user.image = image
            user.save()
            return HttpResponseRedirect(reverse('AppLogin:index'))
    else:
        changeimage_form = ChangeimageForm()
        return render(request,'login/changeuserimage.html',{'form':changeimage_form})

#用户没有登录后要跳转的页面
def loginurl(request):
    return render(request,'login/loginurl.html')

#用户没有权限后要跳转的页面
def nopermisson(request):
    return render(request,'login/nopermission.html')


